package com.stone.framework.core.exception.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.stone.framework.core.exception.BusinessException;
import com.stone.framework.message.ResMessage;

@RestControllerAdvice(basePackages = "com.stone.framework")
public class ControllerExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 处理@RequestBody/@ModelAttribute标记的参数@Valid校验错误抛出的异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    public ResMessage<Void> handArgBindException(Exception e) {
        LOGGER.error(ResMessage.Header.ERROR.toString(), e);
        BindingResult bindingResult = null;
        if (e instanceof BindException) {
            BindException ex = (BindException)e;
            bindingResult = ex.getBindingResult();
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
            bindingResult = ex.getBindingResult();
        }

        String detail = bindingResult.getAllErrors().get(0).getDefaultMessage();
        return ResMessage.fail(detail);
    }

    /**
     * 处理@RequestBody 标记的参数转换异常的问题
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResMessage<Void> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        LOGGER.error(ResMessage.Header.ERROR.toString(), e);
        return ResMessage.fail(e.getMessage());
    }

    /**
     * 处理service层 BusinessException异常
     * 
     * @param e
     *            BusinessException
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResMessage<Void> handleBusinessException(BusinessException e) {
        LOGGER.error(ResMessage.Header.ERROR.toString(), e);
        return ResMessage.fail(e.getMessage());
    }

    /**
     * 处理service层异常
     * 
     * @param e
     *            Exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResMessage<Void> handleException(Exception e) {
        LOGGER.error(ResMessage.Header.ERROR.toString(), e);
        return ResMessage.fail(e.getMessage());
    }

}
